package com.dataart;

import android.app.*;
import android.os.*;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class YahooWeatherService extends Service {
    public static final int INTERVAL = 10000; // 10 sec
    public static final int FIRST_RUN = 5000; // 5 seconds

    private AlarmManager getAlarmManager() {
        return (AlarmManager)this.getSystemService(ALARM_SERVICE);
    }

    private PendingIntent getYahooRequestPendingIntent() {
        return PendingIntent
                .getBroadcast(this, 11223344, new Intent(this, YahooWeatherRequest.class), 0);
    }

    private void startService() {
        getAlarmManager().setRepeating(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + FIRST_RUN,
                INTERVAL,
                getYahooRequestPendingIntent()
        );

        Toast.makeText(this, "Service started.", Toast.LENGTH_LONG).show();
        Log.v(this.getClass().getName(), "AlarmManger started at "
                + new java.sql.Timestamp(System.currentTimeMillis()).toString());

    }

    @Override
    public void onCreate() {
        super.onCreate();
        startService();
        Log.v(this.getClass().getName(), "onCreate(..)");
    }

    @Override
    public void onDestroy() {
        getAlarmManager().cancel(getYahooRequestPendingIntent());

        Toast.makeText(this, "Service Stopped!", Toast.LENGTH_LONG).show();
        Log.v(this.getClass().getName(), "Service onDestroy(). Stop AlarmManager at "
            + new java.sql.Timestamp(System.currentTimeMillis()).toString());
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.v(this.getClass().getName(), "onBind(..)");
        return null;
    }
}
